﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlServerCe;
using System.Data.SqlClient;
using System.IO;
using System.Net;
using System.Data;
using System.Threading.Tasks;
using System.Diagnostics;
using System.Windows.Threading;
using Database = MovieGalleryDLL.DataBase;
using TableAdapters = MovieGalleryDLL.DataBase.MovieDataSetTableAdapters;

namespace MovieGalleryDLL
{
    public class MoviesDB
    {
        static TableAdapters.MoviesTableAdapter adapter;
        static Database.MovieDataSet dataset;
        static Database.MovieDataSet.MoviesDataTable table;

        static MoviesDB()
        {
            adapter = new TableAdapters.MoviesTableAdapter();
            dataset = new Database.MovieDataSet();

            table = adapter.GetData();
        }

        public MoviesDB()
        {
        }

        public List<Movie> GetMovies()
        {
            return (from m in table.AsEnumerable()
                    select new Movie()
                    {
                        ID = m.id,
                        Title = m.title,
                        FilePath = m.filePath,
                        Genre = m.genre,
                        Image = File.Exists(m.imagePath) ? Movie.PathToImage(m.imagePath) : null,
                        IMDB = m.imdb,
                        Like = Convert.ToBoolean(m.like),
                        MD5 = m.md5
                    }).ToList();
        }

        public static void AddMovie(string filePath)
        {
            string fileName, dir, highestDir, imagePath;

            Debug.WriteLine(filePath);

            if (IsMovieAlreadyInDB(filePath))
            {
                return;
            }

            dir = filePath.Substring(0, filePath.LastIndexOf("\\") + 1);
            highestDir = dir;

            if (highestDir.Length > 4)
            {
                highestDir.Substring(4, highestDir.LastIndexOf("\\") - 6);
            }

            fileName = filePath.Substring(filePath.LastIndexOf("\\") + 1);
            fileName = fileName.Substring(0, fileName.LastIndexOf("."));
            fileName = fileName.Replace('.', ' ');
            fileName = fileName.Contains(')') ? fileName.Substring(0, fileName.LastIndexOf(")") + 1) : fileName;
            fileName = fileName.Contains("720p") ? fileName.Substring(0, fileName.LastIndexOf("720p")) : fileName;
            fileName = fileName.Contains("1080p") ? fileName.Substring(0, fileName.LastIndexOf("1080p")) : fileName;

            imagePath = dir + fileName + ".jpg";

            IMDB info = new IMDB(fileName);

            if (info.Title == null && dir.Length > 4)
            {
                highestDir = highestDir.Contains(')') ? highestDir.Substring(0, highestDir.LastIndexOf(")") + 1) : highestDir;
                info = new IMDB(highestDir);
            }

            if (!File.Exists(imagePath) && info.Poster != null)
            {
                if (Path.GetInvalidPathChars().Intersect(imagePath).Count() <= 0)
                {
                    try
                    {
                        new WebClient().DownloadFile(info.Poster, imagePath);
                    }
                    catch (ArgumentException)
                    {
                        Console.WriteLine("ArgumentException: " + imagePath);
                    }
                }
            }

            Database.MovieDataSet.MoviesRow row = table.NewMoviesRow();
            row.title = info.Title == null ? fileName : info.Title;
            row.genre = info.Genres == null ? "None" : info.Genres[0];
            row.like = 0;
            row.imagePath = imagePath;
            row.imdb = info.Id == null ? String.Empty : info.Id;
            row.md5 = String.Empty;
            row.filePath = filePath;

            table.AddMoviesRow(row);
        }

        public static void AddMovies(List<string> listToAdd)
        {
            Parallel.ForEach<string>(listToAdd, element => AddMovie(element));
            adapter.Update(table);
        }

        private static bool IsMovieAlreadyInDB(string path)
        {
            var movies = from m in table where m.filePath == path select m;
            foreach (var m in movies)
            {
                Console.WriteLine("Already in DB: " + path);
                return true;
            }
            return false;
        }
    }
}
